package com.yc.controller;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;

import java.io.IOException;

public class SimpleElasticsearchDemo {

    public static void main(String[] args) {
        // 1. 创建低级客户端
        RestClient restClient = RestClient.builder(
                new HttpHost("localhost", 9200) // ES地址
        ).build();

        // 2. 创建传输层
        RestClientTransport transport = new RestClientTransport(
                restClient,
                new JacksonJsonpMapper() // JSON映射器
        );

        // 3. 创建高级客户端
        ElasticsearchClient client = new ElasticsearchClient(transport);

        try {
            // 4. 测试连接 - 获取集群信息
//            String clusterName = client.cluster().info();
//            System.out.println("Connected to Elasticsearch cluster: " + clusterName);

            // 5. 创建一个简单文档
            String indexName = "test_index";
            String documentId = "1";
            User user = new User("张三", 25);

            client.index(i -> i
                    .index(indexName)
                    .id(documentId)
                    .document(user)
            );

            System.out.println("Document indexed successfully");

            // 6. 查询文档
            User savedUser = client.get(g -> g
                            .index(indexName)
                            .id(documentId),
                    User.class
            ).source();

            System.out.println("Retrieved user: " + savedUser);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 7. 关闭连接
            try {
                restClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 简单的POJO类
    static class User {
        private String name;
        private int age;

        // 必须有默认构造函数和getter/setter
        public User() {}

        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }

        // getter和setter
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        public int getAge() { return age; }
        public void setAge(int age) { this.age = age; }

        @Override
        public String toString() {
            return "User{name='" + name + "', age=" + age + "}";
        }
    }
}